// 通过 zlib 进行文件传输 - todo
#include <event2/event.h>
#include <event2/listener.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/http.h>
#include <iostream>
#include <signal.h>
#include <assert.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <string>
using namespace std;

static const char *ip = "192.168.232.128";
static const int port = 12345;

void req_cb(evhttp_request *req, void *args) {
    cout << "req_cb" << endl;
    bufferevent *bev = (bufferevent*)args;
    if (req == NULL) {
        int errcode = EVUTIL_SOCKET_ERROR();
        cout << "socket error: " << evutil_socket_error_to_string(errcode) << endl;
        return;
    }
    const char* path = evhttp_request_get_uri(req);
    cout << "req path : " << path << endl;
    cout << "reponse: " << evhttp_request_get_response_code(req) << " ";
    cout << evhttp_request_get_response_code_line(req) << endl;

    char buf[1024] = {0};
    evbuffer *input = evhttp_request_get_input_buffer(req);
    while (1) {
        int len = evbuffer_remove(input, buf, sizeof(buf) - 1);
        if (len <= 0) break;
        cout << buf << flush;
    }
}

int main() {
    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
        cerr << "set pipe signal error" << endl;
        return 1;
    }

    event_base *base = event_base_new();
    if (base) {
        cout << "create new event base" << endl;
    }

    // 生成请求
    string http_url = "http://192.168.232.128:8080/index.html";
    evhttp_uri *uri = evhttp_uri_parse(http_url.c_str());
    const char *scheme = evhttp_uri_get_scheme(uri);
    if (!scheme) {
        cerr << "scheme is null" << endl;
        return -1;
    }
    const char *host = evhttp_uri_get_host(uri);

    if (!host) {
        cerr << "host is null" << endl;
        return -1;
    }

    int port = evhttp_uri_get_port(uri);
    cout << "port: " << port << endl;

    const char *path = evhttp_uri_get_path(uri);
    if (!path || strlen(path) == 0) {
        path = "/";
    } else {
        cout << "path: " << path << endl;
    }

    const char *query = evhttp_uri_get_query(uri);
    if (query) {
        cout << "query: " << query << endl;
    } else {
         cout << "query is null"<< endl;
    }

    bufferevent *bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
    evhttp_connection *evcon = evhttp_connection_base_bufferevent_new(base, nullptr, bev, host, port);
    // 创建请求
    evhttp_request *req = evhttp_request_new(req_cb, bev);
    // 设置消息报头
    evkeyvalq *output_headers = evhttp_request_get_output_headers(req);
    evhttp_add_header(output_headers, "Host", host);

    // 发起请求
    evhttp_make_request(evcon, req, EVHTTP_REQ_GET, path);

    // 进入事件主循环
    assert(base);
    event_base_dispatch(base);
    event_base_free(base);

}